package com.cn.onetrip.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.cn.onetrip.objects.ArticleListObj;
import com.cn.onetrip.objects.ArticleObj;
import com.cn.onetrip.objects.VisitsListObj;
import com.cn.onetrip.rorate3d.GalleryAdapter;
import com.cn.onetrip.rorate3d.RouteAtlasGallery;
import com.cn.onetrip.activity.R;
import com.cn.onetrip.translucentblur.Blur;
import com.cn.onetrip.translucentblur.ImageUtils;
import com.cn.onetrip.untility.SBCToDBC;
import com.cn.onetrip.untility.SysApplication;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class RouteAtlasActivity extends Activity {
	private RouteAtlasGallery gallery;
	private GalleryAdapter adapter;
	// private AtlasObj atlasObj;

	private ImageView Atlas_UpImage;
	private TextView textTitle;
	private TextView textViewSubTitle, textViewDesc, textview_page;
	public RelativeLayout layout, bottomLayout;
	public RelativeLayout backGroundLayout;
	public Button returnButton;
	public boolean showText = true;
	private int num = 0;
	List<String> url = new ArrayList<String>();

	private String subTitles[], texts[], imageUrl[];
	RelativeLayout layoutTitle;
	private int count = 0;
	private ProgressBar pb;
	private int loadImageCount;
	public final int loadImageSize = 5;
	public boolean isLastLoad = false;
	private int startLocal = 700;
	private int endLocal = 0;
	private int endUpLocal = 0;
	private int tmp = 0;
	private int windowWidth;
	private int windowHeight;

	private long downTime, upTime;

	private int layoutHeight;
	private int bgHeight;

	private int y1 = -1;
	private int y2 = -1;
	private final float param = 0.1f;
	private int aDuration = 0;

	// RelativeLayout.LayoutParams layoutParams = null;

	int marginTop = 0;

	private static final String BLURRED_IMG_PATH = "blurred_image.png";
	// private ImageView mBlurredImage;
	private float alpha;
	private int screenWidth;
	private boolean isChange = false;
	private ImageView translucency;
	private int selecterID = 10000;
	private RelativeLayout.LayoutParams Params = null;
	private int topLocation = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		if (SysApplication.visitsListObj.size() == 0) {
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}

		setContentView(R.layout.activity_route_atlas);
		// windowWidth = getWindowManager().getDefaultDisplay().getWidth();
		windowHeight = getWindowManager().getDefaultDisplay().getHeight();
		screenWidth = ImageUtils.getScreenWidth(this);
		// mBlurredImage = (ImageView) findViewById(R.id.blurred_image);

		layoutTitle = (RelativeLayout) findViewById(R.id.layout_title);
		backGroundLayout = (RelativeLayout) findViewById(R.id.backgroundLayout);
		bottomLayout = (RelativeLayout) findViewById(R.id.bottomLayout);
		Atlas_UpImage = (ImageView) findViewById(R.id.Atlas_UpImage);
		// layoutHeight = getResources().getInteger(
		// R.integer.RouteDetail_Text_widthpixel);
		layoutHeight = 3 * windowHeight / 4;
		bgHeight = layoutHeight - layoutTitle.getHeight();
		layout = (RelativeLayout) findViewById(R.id.Route_Atlas_RelativeLayout);

		textTitle = (TextView) findViewById(R.id.text_title);
		textViewSubTitle = (TextView) findViewById(R.id.textview_subTitle);
		textViewDesc = (TextView) findViewById(R.id.textview_desc);
		textview_page = (TextView) findViewById(R.id.textview_page);
		pb = (ProgressBar) findViewById(R.id.atlas_pb);
		translucency = (ImageView) findViewById(R.id.translucency);

		Params = (RelativeLayout.LayoutParams) layout.getLayoutParams();
		Params.topMargin = layoutHeight;
		layout.setLayoutParams(Params);
		layout.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout
						.getLayoutParams();
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					layout.clearAnimation();
					downTime = System.currentTimeMillis();
					endLocal = (int) event.getRawY();
					startLocal = layout.getTop();
					tmp = endLocal - startLocal;
					break;
				case MotionEvent.ACTION_MOVE:
					// mBlurredImage.setVisibility(View.VISIBLE);
					int y_cord = (int) event.getRawY();
					int distance = layout.getTop();
					marginTop = y_cord - tmp;
					if (marginTop > layoutHeight) {
						Atlas_UpImage.setVisibility(View.VISIBLE);
					} else if (marginTop <= 0) {
						if (layout.getBottom() > bottomLayout.getTop()) {
							y1 = marginTop;
							layoutParams.topMargin = marginTop;
							layout.setLayoutParams(layoutParams);
						} else {
							y2 = marginTop;
							if (y2 > y1) {
								layoutParams.topMargin = marginTop;
								layout.setLayoutParams(layoutParams);
							}
						}
						Atlas_UpImage.setVisibility(View.INVISIBLE);
					} else {
						layoutParams.topMargin = marginTop;
						layout.setLayoutParams(layoutParams);
						Atlas_UpImage.setVisibility(View.INVISIBLE);
					}

					// alpha = (float) -headerView.getTop() / (float)
					// TOP_HEIGHT;
					alpha = (float) (layoutHeight - layout.getTop()) * 2
							/ (float) layoutHeight;
					if (alpha > 1) {
						alpha = 1;
					}
					// mBlurredImage.setAlpha((int) (alpha * 255));
					// getGallery().setAlphaPH(alpha);

					changeBackground(marginTop);

					break;
				case MotionEvent.ACTION_UP:
					upTime = System.currentTimeMillis();
					endUpLocal = (int) event.getRawY();
					float distanceTime = upTime - downTime;
					// (distancePx > 0) pull down
					float distancePx = endUpLocal - endLocal;
					float dif = distancePx / distanceTime;

					// 加速度 a
					float a = distancePx * 1000 * 1000
							/ (2 * distanceTime * distanceTime);

					// aDuration = (int) Math.abs(a) / 3;
					// setAnimTranslation(a, marginTop, aDuration);

					if (distancePx >= 0) {
						// if (dif >= 0.6) {
						if (a >= 900) {
							marginTop = layoutHeight;
							layoutParams.topMargin = layoutHeight;
							layout.setLayoutParams(layoutParams);
							changeBackground(marginTop);
							Atlas_UpImage.setVisibility(View.VISIBLE);
							// mBlurredImage.setAlpha(0);
							// getGallery().setAlphaPH(0.0f);
						}
						// } else if (-dif >= 0.6) {
					} else if (-a >= 900) {
						marginTop = 0;
						layoutParams.topMargin = marginTop;
						layout.setLayoutParams(layoutParams);
						changeBackground(marginTop);
						// mBlurredImage.setAlpha(255);
						// getGallery().setAlphaPH(1.0f);
					}
					break;
				default:
					break;
				}
				return true;
			}
		});

		loadData();

		adapter = new GalleryAdapter(RouteAtlasActivity.this, mHandler,
				imageUrl, texts);

		if (imageUrl.length != 0) {
			selecterID = Integer.MAX_VALUE / 2
					- (Integer.MAX_VALUE / 2 % imageUrl.length);
		}
		// adapter = new GalleryAdapter(this, atlasObj);
		setGallery((RouteAtlasGallery) findViewById(R.id.gallery));
		getGallery().setVerticalFadingEdgeEnabled(false);
		getGallery().setHorizontalFadingEdgeEnabled(false);
		getGallery().setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				num = arg2;
				// Message msg = Message.obtain();
				// msg.what = 2;
				// mHandler.sendMessage(msg);
				startThread();
				if (Params != null) {
					Params.topMargin = layoutHeight;
					layout.setLayoutParams(Params);
					Atlas_UpImage.setVisibility(View.VISIBLE);
					changeBackground(layoutHeight);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		getGallery().setHandler(mHandler);

		returnButton = (Button) findViewById(R.id.quit);
		returnButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
				System.gc();
				overridePendingTransition(R.anim.push_left_translate,
						R.anim.pull_right_translate);
			}
		});
		GalleryWhetherStop();
	}

	public void setBlurImage() {
		for (int i = 0; i < imageUrl.length; i++) {
			final File blurredImage = new File(getFilesDir()
					+ splitString(imageUrl[i % imageUrl.length]));
			final int j = i;
			if (!blurredImage.exists()) {
				// launch the progressbar in ActionBar
				setProgressBarIndeterminateVisibility(true);
				new Thread(new Runnable() {
					@Override
					public void run() {
						// No image found => let's generate it!
						BitmapFactory.Options options = new BitmapFactory.Options();
						options.inSampleSize = 2;
						Bitmap image = GalleryAdapter.imagesCache
								.get(imageUrl[j % imageUrl.length]);
						Bitmap newImg = null;
						try {
							newImg = Blur.fastblur(RouteAtlasActivity.this,
									image, 12);
							ImageUtils.storeImage(newImg, blurredImage);
						} catch (OutOfMemoryError e) {
							// newImg = BitmapFactory.decodeResource(
							// getResources(), R.drawable.rc_item_bg,
							// options);
						}

						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								updateView(screenWidth, j);
								// And finally stop the progressbar
								setProgressBarIndeterminateVisibility(false);
								adapter.notifyDataSetChanged();
							}
						});
					}
				}).start();

			} else {
				// The image has been found. Let's update the view
				updateView(screenWidth, j);
				adapter.notifyDataSetChanged();
			}
		}
	}

	private void updateView(final int screenWidth, int position) {

		BitmapFactory.Options options = new BitmapFactory.Options();
		Bitmap bmpBlurred = null;
		int optSize = 2;
		try {
			// bmpBlurred = BitmapFactory.decodeFile(getFilesDir()
			// + splitString(imageUrl[position % imageUrl.length]));
			options.inSampleSize = optSize;
			bmpBlurred = BitmapFactory.decodeFile(getFilesDir()
					+ splitString(imageUrl[position % imageUrl.length]),
					options);
		} catch (OutOfMemoryError e) {
			options.inSampleSize = optSize * optSize;
			bmpBlurred = BitmapFactory.decodeFile(getFilesDir()
					+ splitString(imageUrl[position % imageUrl.length]),
					options);
		}
		if (bmpBlurred == null) {
			return;
		}
		if (!GalleryAdapter.imagesBlurCache
				.containsKey(splitString(imageUrl[position % imageUrl.length]))) {
			GalleryAdapter.imagesBlurCache.put(splitString(imageUrl[position
					% imageUrl.length]), bmpBlurred);
		}
		// mBlurredImage.setImageBitmap(bmpBlurred);
	}

	public String splitString(String string) {
		String split = "";
		String s = new String(string);
		String a[] = s.split("/");
		split = a[a.length - 1];
		return split;
	}

	private void setAnimTranslation(float a, final int maginTop, int duration) {
		final int distance = (int) (a * param);
		layout.clearAnimation();
		TranslateAnimation tAnimation = new TranslateAnimation(0, 0, 0,
				distance);
		// tAnimation.setFillAfter(true);
		tAnimation.setInterpolator(new DecelerateInterpolator());
		tAnimation.setDuration(duration);
		layout.setAnimation(tAnimation);

		tAnimation.start();
		tAnimation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				layout.clearAnimation();
				RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout
						.getLayoutParams();
				int toTop = (maginTop + distance);
				if (toTop <= 50) {
					toTop = 50;
				} else if (toTop >= layoutHeight) {
					toTop = layoutHeight;
				}
				layoutParams.topMargin = toTop;
				layout.setLayoutParams(layoutParams);
			}
		});
	}

	private int itemId, routeNum;
	private String tag, itemTitle, itemTime, itemSource;

	private void loadData() {
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		itemId = bundle.getInt("itemId");
		routeNum = bundle.getInt("route_num");
		List<ArticleObj> ArticleList = null;
		List<VisitsListObj> visitsListObj = SysApplication.visitsListObj;
		VisitsListObj visitsList = visitsListObj.get(routeNum);
		List<ArticleListObj> articlesListObj = visitsList.detailedsSites;
		ArticleListObj articleList = articlesListObj.get(itemId);
		ArticleList = articleList.detailedsArticleList;

		subTitles = new String[ArticleList.size()];
		texts = new String[ArticleList.size()];
		imageUrl = new String[ArticleList.size()];
		for (int i = 0; i < ArticleList.size(); i++) {
			ArticleObj articleObj = ArticleList.get(i);
			subTitles[i] = articleObj.title;
			texts[i] = articleObj.description;
			imageUrl[i] = articleObj.icon;
		}
	}

	/**
	 */
	private void GalleryWhetherStop() {
		Runnable runnable = new Runnable() {
			public void run() {
				try {
					Message m = Message.obtain();
					m.what = 1;
					mHandler.sendMessage(m);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(runnable).start();
	}

	class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = null;
			try {
				String url = params[0];
				GalleryAdapter.loadImageFromUrl(url);
				Thread.sleep(200);

				count++;
				if (count == imageUrl.length) {
					count = 0;
					Thread.sleep(500);
					Message m = Message.obtain();
					m.what = 0;
					mHandler.sendMessage(m);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return bitmap;
		}
	}

	private boolean isFirstLoad = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case 0: {
					if (!isFirstLoad) {
						isFirstLoad = true;
						getGallery().setAdapter(adapter);
						getGallery().setSelection(selecterID);
						// setBlurImage();
						adapter.notifyDataSetChanged();
						pb.setVisibility(View.GONE);
					}
					break;
				}
				case 1: {
					for (int i = 0; i < imageUrl.length; i++) {
						LoadImageTask task = new LoadImageTask();
						task.execute(imageUrl[i]);
					}
				}
				case 2: {
					if (isFirstLoad) {
						setTextViewContent();
						// if (isChange) {
						// final File blurredImage = new File(getFilesDir()
						// + splitString(imageUrl[num
						// % imageUrl.length]));
						// if (!blurredImage.exists()) {
						// // launch the progressbar in ActionBar
						//
						// setProgressBarIndeterminateVisibility(true);
						// new Thread(new Runnable() {
						// @Override
						// public void run() {
						// // No image found => let's generate it!
						// BitmapFactory.Options options = new
						// BitmapFactory.Options();
						// options.inSampleSize = 2;
						// // Bitmap image =
						// // BitmapFactory.decodeResource(
						// // getResources(), R.drawable.image,
						// // options);
						// Bitmap image = GalleryAdapter.imagesCache
						// .get(imageUrl[num
						// % imageUrl.length]);
						// Bitmap newImg = null;
						// try {
						// newImg = Blur.fastblur(
						// RouteAtlasActivity.this,
						// image, 12);
						// ImageUtils.storeImage(newImg,
						// blurredImage);
						// } catch (OutOfMemoryError e) {
						// // newImg = BitmapFactory
						// // .decodeResource(
						// // getResources(),
						// // R.drawable.rc_item_bg,
						// // options);
						// }
						// runOnUiThread(new Runnable() {
						// @Override
						// public void run() {
						// updateView(screenWidth, num);
						// // And finally stop the
						// // progressbar
						// setProgressBarIndeterminateVisibility(false);
						// }
						// });
						// }
						// }).start();
						//
						// } else {
						// // The image has been found. Let's update the
						// // view
						// updateView(screenWidth, num);
						// }
						// updateView(screenWidth, num);
						// } else {
						// isChange = true;
						// }
					}

				}

				case 3: {
					// mBlurredImage.setVisibility(View.INVISIBLE);
				}
				}
				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private void startThread() {
		ChangeImageThread changeImageThread = new ChangeImageThread();
		Thread thread = new Thread(changeImageThread);
		thread.start();
	}

	public class ChangeImageThread implements Runnable {

		public ChangeImageThread() {
		}

		@Override
		public void run() {
			Message msg = Message.obtain();
			msg.what = 2;
			mHandler.sendMessage(msg);
		}
	}

	public void setTextViewState() {
		if (showText) {
			// bottomLayout.setAnimation(AnimationUtils.loadAnimation(
			// getApplicationContext(), R.anim.pull_bottom_translate));
			layoutTitle.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.pull_top_translate));
			layout.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.pull_bottom_translate));
			translucency.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.pull_bottom_translate));
			// bottomLayout.setVisibility(View.GONE);
			layoutTitle.setVisibility(View.GONE);
			layout.setVisibility(View.GONE);
			translucency.setVisibility(View.GONE);
			backGroundLayout.setBackgroundColor(Color.argb(0, 0, 0, 0));
			showText = false;
		} else {
			// bottomLayout.setAnimation(AnimationUtils.loadAnimation(
			// getApplicationContext(), R.anim.push_bottom_translate));
			layoutTitle.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_top_translate));
			layout.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_bottom_translate));
			translucency.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_bottom_translate));
			// bottomLayout.setVisibility(View.VISIBLE);
			layoutTitle.setVisibility(View.VISIBLE);
			layout.setVisibility(View.VISIBLE);
			translucency.setVisibility(View.VISIBLE);
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
			showText = true;
		}
	}

	public void setTextViewContent() {
		Atlas_UpImage.setBackgroundResource(R.drawable.route_subtitle_image);
		// String subTitle = subTitles[num % subTitles.length];
		// String description = texts[num % texts.length];
		textViewSubTitle.setText(SBCToDBC.ToDBC(subTitles[num
				% subTitles.length]));
		textViewDesc.setText(SBCToDBC.ToDBC(texts[num % texts.length]));
		if (layout.getVisibility() == View.VISIBLE) {
			layout.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_bottom_translate));
			textViewSubTitle.setVisibility(View.VISIBLE);
			translucency.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_bottom_translate));
			translucency.setVisibility(View.VISIBLE);
		}
		textview_page.setText((num % imageUrl.length + 1) + "/"
				+ imageUrl.length);
	}

	int bgColor = 0;

	private void changeBackground(int marginTop) {
		if (marginTop >= 0 && marginTop <= bgHeight / 20) {
			bgColor = 190;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > bgHeight / 20
				&& marginTop <= (bgHeight * 2 / 20)) {
			bgColor = 180;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 2 / 20)
				&& marginTop <= (bgHeight * 3 / 20)) {
			bgColor = 170;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 3 / 20)
				&& marginTop <= (bgHeight * 4 / 20)) {
			bgColor = 160;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 4 / 20)
				&& marginTop <= (bgHeight * 5 / 20)) {
			bgColor = 150;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 5 / 20)
				&& marginTop <= (bgHeight * 6 / 20)) {
			bgColor = 140;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 6 / 20)
				&& marginTop <= (bgHeight * 7 / 20)) {
			bgColor = 130;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 7 / 20)
				&& marginTop <= (bgHeight * 8 / 20)) {
			bgColor = 120;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 8 / 20)
				&& marginTop <= (bgHeight * 9 / 20)) {
			bgColor = 110;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 9 / 20)
				&& marginTop <= (bgHeight * 10 / 20)) {
			bgColor = 100;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 10 / 20)
				&& marginTop <= (bgHeight * 11 / 20)) {
			bgColor = 90;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 11 / 20)
				&& marginTop <= (bgHeight * 12 / 20)) {
			bgColor = 80;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 12 / 20)
				&& marginTop <= (bgHeight * 13 / 20)) {
			bgColor = 70;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 13 / 20)
				&& marginTop <= (bgHeight * 14 / 20)) {
			bgColor = 60;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 14 / 20)
				&& marginTop <= (bgHeight * 15 / 20)) {
			bgColor = 50;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 15 / 20)
				&& marginTop <= (bgHeight * 16 / 20)) {
			bgColor = 40;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 16 / 20)
				&& marginTop <= (bgHeight * 17 / 20)) {
			bgColor = 30;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 17 / 20)
				&& marginTop <= (bgHeight * 18 / 20)) {
			bgColor = 20;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 18 / 20)
				&& marginTop <= (bgHeight * 19 / 20)) {
			bgColor = 10;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		} else if (marginTop > (bgHeight * 19 / 20) && marginTop <= (bgHeight)) {
			bgColor = 0;
			backGroundLayout.setBackgroundColor(Color.argb(bgColor, 0, 0, 0));
		}
	}

	public RouteAtlasGallery getGallery() {
		return gallery;
	}

	public void setGallery(RouteAtlasGallery gallery) {
		this.gallery = gallery;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			overridePendingTransition(R.anim.push_left_translate,
					R.anim.pull_right_translate);
			System.gc();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		GalleryAdapter.imagesCache.clear();
		super.onDestroy();
	}

}
